package com.example.dql.diary.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.dql.diary.R;
import com.example.dql.diary.Utils.WebViewManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WebViewActivity extends BaseActivity {

	@BindView(R.id.button_back)
	ImageView buttonBack;
	@BindView(R.id.webView)
	WebView mWebView;
	@BindView(R.id.progressBar)
	ProgressBar mProgressBar;

	@Override
	public int getLayoutId() {
		return R.layout.activity_web_view;
	}

	@Override
	public Activity bindActivity() {
		return this;
	}

	@Override
	public void init() {
		WebViewManager manager = new WebViewManager(mWebView);
		manager.enableAdaptive();
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setBlockNetworkImage(false);
		mWebView.loadUrl("https://m.gitee.com/TongGuJuShi");
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return false;
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed();// 接受所有网站的证书
			}

		});
		mWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				if (newProgress < 100) {
					mProgressBar.setProgress(newProgress);
				} else if (newProgress == 100) {
					mProgressBar.setVisibility(View.GONE);
				}
			}
		});
		mWebView.setDownloadListener(new MyWebViewDownLoadListener());

	}
	private class MyWebViewDownLoadListener implements DownloadListener {
		@Override
		public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
			Uri uri = Uri.parse(url);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}
	}

	@OnClick({R.id.button_back, R.id.button_refresh})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.button_back:
				finish();
				break;
			case R.id.button_refresh:
				break;
		}
	}

	//点击返回键不是退出而是返回到上一界面
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
